package com.study.cloud;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wangwancheng
 * @create 2025/7/18 22:16
 */
public class ChatServerHandler extends SimpleChannelInboundHandler {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        Channel channel = channelHandlerContext.channel();
        channelGroup.forEach(ch -> {
            if (ch != channel){
                ch.writeAndFlush(sdf.format(new Date()) +" "+channel.remoteAddress() +" 发送消息:"+o+"\n");
            }else {
                ch.writeAndFlush(sdf.format(new Date()) + " 自己发送消息:"+o+"\n");
            }
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        channelGroup.writeAndFlush(sdf.format(new Date()) + " 客户端:"+channel.remoteAddress()+"已上线,请注意接受消息\n");
        System.out.println(sdf.format(new Date()) + " 添加客户端:"+channel.remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.remove( channel);
        channelGroup.writeAndFlush(sdf.format(new Date()) + " 客户端:"+channel.remoteAddress()+"已下线\n");
        System.out.println(sdf.format(new Date()) + " 删除客户端:"+channel.remoteAddress());
        System.out.println(sdf.format(new Date()) + " 在线人数:"+channelGroup.size());

    }
}
